﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Data.Linq;
using System.Data.Common;
using TSV.Library.Common;
using TSV.Models;

namespace TSV.Models
{
    public class PartnerDao : BaseDao
    {
        public Partner GetPartnerByID(int id)
        {
            return dbContext.Partners.Where(q => q.ID == id && q.DeleteFlag == false).FirstOrDefault();
        }

        public List<sp_GetGlobalSearchResult> GetListByGlobalSearch(string text, int category,int province,int district)
        {
            return dbContext.sp_GetGlobalSearch(text, category,province,district).ToList();
        }

        public PartnerAddress GetMainPartnerAddressByPartnerID(int partnerID)
        {
            return dbContext.PartnerAddresses.Where(q => q.IsMainAddress == true && q.PartnerID == partnerID).FirstOrDefault();
        }

        public List<sp_GetPromotionPartnerResult> GetListPromotionPartner()
        {
            return dbContext.sp_GetPromotionPartner().ToList<sp_GetPromotionPartnerResult>();
        }

        public List<Partner> GetListNewPartner()
        {
            return dbContext.Partners.Where(q => q.IsNew == true && q.DeleteFlag == false && q.IsActive == true).OrderByDescending(q => q.PartnerOrder).ToList();
        }

        public List<sp_GetPartnerResult> GetPartner(string text, int category, int province, int district)
        {
            return dbContext.sp_GetPartner(text, category, province, district).ToList();
        }

        public List<Partner> GetPartnerList(int categoryID)
        {
            return dbContext.Partners.Where(q => q.CategoryID == categoryID && q.DeleteFlag == false).OrderByDescending(c => c.PartnerOrder).ToList();
        }

        public sp_GetMainPartnerAddressResult GetMainPartnerAddress(int partnerID)
        {
            return dbContext.sp_GetMainPartnerAddress(partnerID).FirstOrDefault();
        }

        public List<sp_GetPartnerAddressListResult> GetPartnerAddressList(int partnerID)
        {
            return dbContext.sp_GetPartnerAddressList(partnerID).ToList();
        }

        public List<Gallery> GetPartnerGallery(int partnerID)
        {
            return dbContext.Galleries.Where(q => q.PartnerID == partnerID && q.IsShownFrontEnd == true).OrderBy(c=> c.ImageOrder).ToList<Gallery>();
        }

        public List<Promotion> GetPartnerPromotion(int partnerID)
        {
            return dbContext.Promotions.Where(q => q.PartnerID == partnerID && q.Active == true).OrderBy(q => q.PromotionOrder).ToList();
        }

        public List<District> GetDistristByProvince(int provinceID)
        {
            return dbContext.Districts.Where(q => q.ProvinceID == provinceID).ToList();
        }

        public List<PartnerAddress> GetAddressListByPartnerID(int partnerID)
        {
            return dbContext.PartnerAddresses.Where(c => c.PartnerID == partnerID).ToList<PartnerAddress>();
        }
        public List<Partner> GetAllPartnerList()
        {
            return dbContext.Partners.Where(c=>c.DeleteFlag==false).ToList<Partner>();
            
        }
        public Message UpdateImage(Partner objUI)
        {
            Message msg = null;
            try
            {
                if (objUI != null)
                {
                    Partner objDb = GetPartnerByID(objUI.ID);

                    if (objDb != null)
                    {
                        objDb.Logo = objUI.Logo;
                        objDb.UpdateDate = DateTime.Now;
                        objDb.UpdatedBy = objUI.UpdatedBy;
                        dbContext.SubmitChanges();

                        msg = new Message(MessageConstants.I0001, MessageType.Info, "logo đối tác", "cập nhật");

                    }
                }
            }
            catch
            {
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        public List<sp_GetPartnerListResult> GetList(string text, int? categoryID, DateTime? fromDate, DateTime? toDate, bool? expired)
        {
            return dbContext.sp_GetPartnerList(text, categoryID, fromDate, toDate, expired).ToList<sp_GetPartnerListResult>();
        }

        /// <summary>
        /// Sort Product
        /// </summary>
        /// <param name="list"></param>
        /// <param name="sortColumn"></param>
        /// <param name="sortOrder"></param>
        /// <returns></returns>
        public List<sp_GetPartnerListResult> Sort(List<sp_GetPartnerListResult> list, string sortColumn, string sortOrder)
        {
            int order;

            if (sortOrder == "desc")
            {
                order = -1;
            }
            else
            {
                order = 1;
            }
            switch (sortColumn)
            {
                case "PartnerName":
                    list.Sort(
                         delegate(sp_GetPartnerListResult m1, sp_GetPartnerListResult m2)
                         { return m1.PartnerName.CompareTo(m2.PartnerName) * order; });
                    break;
                case "Category":
                    list.Sort(
                         delegate(sp_GetPartnerListResult m1, sp_GetPartnerListResult m2)
                         { return m1.CategoryName.CompareTo(m2.CategoryName) * order; });
                    break;
                case "PartnerOrder":
                    list.Sort(
                         delegate(sp_GetPartnerListResult m1, sp_GetPartnerListResult m2)
                         { return m1.PartnerOrder.CompareTo(m2.PartnerOrder) * order; });
                    break;
                case "CreateDate":
                    list.Sort(
                         delegate(sp_GetPartnerListResult m1, sp_GetPartnerListResult m2)
                         { return m1.CreateDate.CompareTo(m2.CreateDate) * order; });
                    break;
                case "UpdateDate":
                    list.Sort(
                         delegate(sp_GetPartnerListResult m1, sp_GetPartnerListResult m2)
                         { return m1.UpdateDate.CompareTo(m2.UpdateDate) * order; });
                    break;
            }

            return list;
        }

        public int GetLastID()
        {
            int lastID = 1;
            try
            {
                lastID = dbContext.Partners.OrderByDescending(c => c.ID).Select(c => c.ID).FirstOrDefault<int>();
            }
            catch (Exception)
            {

            }
            return lastID;
        }

        public int GetLastOrder()
        {
            int lastOrder = 1;
            try
            {
                lastOrder = dbContext.Partners.Where(c=> c.DeleteFlag == false).OrderByDescending(c => c.PartnerOrder).Select(c => c.PartnerOrder).FirstOrDefault<int>();
            }
            catch (Exception)
            {

            }
            return lastOrder;
        }

        public Message Insert(Partner objUI, List<PartnerAddress> addressList)
        {
            Message msg = null;
            try
            {
                if (objUI != null)
                {
                    //insert and get it's id
                    int partnerId = Insert(objUI);
                    if (partnerId != 0)
                    {
                        foreach (PartnerAddress address in addressList)
                        {
                            address.PartnerID = partnerId;
                        }
                        dbContext.PartnerAddresses.InsertAllOnSubmit(addressList);
                        dbContext.SubmitChanges();
                    }

                    // Show success message
                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Ðối tác '" + objUI.PartnerName + "'", "thêm");
                }
            }
            catch (Exception)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }


        public Message Update(Partner objUI, List<PartnerAddress> addressList)
        {
            Message msg = null;
            DbTransaction trans = null;
            try
            {
                dbContext.Connection.Open();
                trans = dbContext.Connection.BeginTransaction();
                dbContext.Transaction = trans;
                Partner objDb = GetPartnerByID(objUI.ID);
                if (objDb != null)
                {
                    objDb.Logo = objUI.Logo;
                    objDb.PartnerName = objUI.PartnerName;
                    objDb.CategoryID = objUI.CategoryID;
                    objDb.Webiste = objUI.Webiste;
                    objDb.Email = objUI.Email;
                    objDb.Description = objUI.Description;
                    objDb.DiscountInfo = objUI.DiscountInfo;
                    objDb.Representative = objUI.Representative;
                    objDb.RepresentativePhone = objUI.RepresentativePhone;
                    objDb.ExpireDate = objUI.ExpireDate;
                    objDb.UpdatedBy = objUI.UpdatedBy;
                    objDb.UpdateDate = DateTime.Now;

                    dbContext.SubmitChanges();

                    List<PartnerAddress> deletedList = GetAddressListByPartnerID(objUI.ID);
                    if (deletedList.Count > 0)
                    {
                        dbContext.PartnerAddresses.DeleteAllOnSubmit(deletedList);
                        dbContext.SubmitChanges();
                    }
                    dbContext.PartnerAddresses.InsertAllOnSubmit(addressList);
                    dbContext.SubmitChanges();

                    trans.Commit();
                    // Show success message
                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Ðối tác '" + objUI.PartnerName + "'", "cập nhật");
                }
            }
            catch (Exception)
            {
                if (trans != null) trans.Rollback();
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        /// <summary>
        /// Insert a question without answer
        /// </summary>
        /// <param name="question"></param>
        /// <returns>int</returns>
        public int Insert(Partner partner)
        {
            int result = 0;
            try
            {
                if (partner != null)
                {
                    dbContext.Partners.InsertOnSubmit(partner);
                    //Submit changes to database
                    dbContext.SubmitChanges();
                    result = partner.ID;
                }
            }
            catch
            {
                result = 0;
            }
            return result;
        }

        /// <summary>
        /// DeleteList
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public Message DeleteList(string ids)
        {
            Message msg = null;
            DbTransaction trans = null;
            try
            {
                dbContext.Connection.Open();
                trans = dbContext.Connection.BeginTransaction();
                dbContext.Transaction = trans;

                if (!string.IsNullOrEmpty(ids))
                {
                    bool canDelete = true;
                    ids = ids.TrimEnd(',');
                    int collaboratorID = 0;

                    List<string> imageList = new List<string>();
                    string[] idArr = ids.Split(',');
                    int total = idArr.Count();
                    foreach (string id in idArr)
                    {
                        bool isValid = Int32.TryParse(id, out collaboratorID);
                        Partner partner = GetPartnerByID(collaboratorID);
                        if (partner != null)
                        {
                            bool isSuccess = Delete(partner);
                            imageList.Add(partner.Logo);
                            if (!isSuccess)
                            {
                                canDelete = false;
                                // Show succes message
                                msg = new Message(MessageConstants.E0006, MessageType.Error, "xóa", "đối tác này");
                                break;
                            }
                        }
                        else
                        {
                            total--;
                        }
                    }

                    if (canDelete)
                    {
                        // Show succes message
                        msg = new Message(MessageConstants.I0001, MessageType.Info, total.ToString() + " đối tác", "xóa");
                        trans.Commit();

                        //Delete image
                        foreach (string img in imageList)
                        {
                            if (!string.IsNullOrEmpty(img) && img != Constants.NO_IMAGE)
                            {
                                string strPath = HttpContext.Current.Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER) + img;
                                //strPath += "\\" + image;
                                if (System.IO.File.Exists(strPath))
                                    System.IO.File.Delete(strPath);
                            }
                        }
                    }
                    else
                    {
                        trans.Rollback();
                    }
                }
            }
            catch (Exception)
            {
                if (trans != null) trans.Rollback();
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        /// <summary>
        /// Delete
        /// </summary>
        /// <param name="objUI"></param>
        private bool Delete(Partner objUI)
        {
            bool result = true;
            if (objUI != null)
            {
                // Get current group in dbContext
                Partner objDb = GetPartnerByID(objUI.ID);
                if (objDb != null)
                {
                    // Set delete info                    
                    objDb.DeleteFlag = true;
                    objDb.UpdateDate = DateTime.Now;
                    objDb.UpdatedBy = objUI.UpdatedBy;
                    // Submit changes to dbContext
                    dbContext.SubmitChanges();
                }
                else
                {
                    result = false;
                }
            }
            return result;
        }

        public Message MovePartnerUp(Partner objUI)
        {
            Message msg = null;
            try
            {
                if (objUI != null)
                {
                    // Get current group in dbContext
                    Partner objCurrent = GetByOrder(objUI.PartnerOrder);
                    Partner objNext = GetByOrder(objUI.PartnerOrder + 1);

                    if (objCurrent != null && objNext != null)
                    {
                        int currentOrder = objCurrent.PartnerOrder;
                        int nextOrder = objNext.PartnerOrder;
                        // Update info by objUI
                        objCurrent.PartnerOrder = nextOrder;
                        objNext.PartnerOrder = currentOrder;

                        // Submit changes to dbContext
                        dbContext.SubmitChanges();
                        // Show success message
                        msg = new Message(MessageConstants.I0001, MessageType.Info, "Đối tác ", "cập nhật thứ tự");

                    }
                    else
                    {
                        // Show system error
                        msg = new Message(MessageConstants.E0007, MessageType.Error);
                    }
                }
            }
            catch (Exception)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }

            return msg;
        }

        public Message MovePartnerDown(Partner objUI)
        {
            Message msg = null;
            try
            {
                if (objUI != null)
                {
                    // Get current group in dbContext
                    Partner objCurrent = GetByOrder(objUI.PartnerOrder);
                    Partner objPrevious = GetByOrder(objUI.PartnerOrder - 1);

                    if (objCurrent != null && objPrevious != null)
                    {
                        int currentOrder = objCurrent.PartnerOrder;
                        int previousOrder = objPrevious.PartnerOrder;
                        // Update info by objUI
                        objCurrent.PartnerOrder = previousOrder;
                        objPrevious.PartnerOrder = currentOrder;

                        // Submit changes to dbContext
                        dbContext.SubmitChanges();
                        // Show success message
                        msg = new Message(MessageConstants.I0001, MessageType.Info, "Đối tác ", "cập nhật thứ tự");

                    }
                    else
                    {
                        // Show system error
                        msg = new Message(MessageConstants.E0007, MessageType.Error);
                    }
                }
            }
            catch (Exception)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }

            return msg;
        }

        public Partner GetByOrder(int order)
        {
            return dbContext.Partners.Where(c => c.PartnerOrder == order && c.DeleteFlag == false).FirstOrDefault<Partner>();
        }

        public Message UpdateIsNewPartner(int id)
        {
            Message msg = null;
            try
            {

                // Get current group in dbContext
                Partner objDb = GetPartnerByID(id);

                if (objDb != null)
                {
                    // Update info by objUI
                    if (objDb.IsNew)
                    {
                        objDb.IsNew = false;
                    }
                    else
                    {
                        objDb.IsNew = true;
                    }
                    // Submit changes to dbContext
                    dbContext.SubmitChanges();
                    // Show success message
                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Đối tác ", "cập nhật");


                }
            }
            catch (Exception)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }

            return msg;
        }

        public Message UpdateIsActive(int id)
        {
            Message msg = null;
            try
            {

                // Get current group in dbContext
                Partner objDb = GetPartnerByID(id);

                if (objDb != null)
                {
                    // Update info by objUI
                    objDb.IsActive = !objDb.IsActive;                    
                    // Submit changes to dbContext
                    dbContext.SubmitChanges();
                    // Show success message
                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Đối tác ", "cập nhật");


                }
            }
            catch (Exception)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }

            return msg;
        }
    }
}